package com.xiaogao.autofill.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiaogao.common.utils.token.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;
    @Override
    public void insertFill(MetaObject metaObject) {
        String token = request.getHeader("token");
        // 这里可以设置插入时的字段值
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("createBy", JwtUtils.userId(token), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String token = request.getHeader("token");
        // 这里可以设置更新时的字段值
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", JwtUtils.userId(token), metaObject);
    }
}
